package cn.xueden.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.Collections;

/**功能描述：跨域配置
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.config
 * @version:1.0
 */
@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1.允许任何来源
        corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        //2.允许任何请求头
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
        //3.允许任何方法
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        //4.允许凭证
        corsConfiguration.setAllowCredentials(true);
        // 5. 关键配置：暴露响应头（否则前端拿不到Content-Disposition）
        corsConfiguration.setExposedHeaders(Arrays.asList(
                "Content-Disposition",
                "Authorization",
                "Cache-Control",
                "Content-Type"
        ));

        // 创建 UrlBasedCorsConfigurationSource 对象，用于管理跨域配置。
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 将跨域配置注册到 UrlBasedCorsConfigurationSource 对象中，并指定要拦截的 URL
        source.registerCorsConfiguration("/**", corsConfiguration);
        // 创建 CorsFilter 对象，并传入 UrlBasedCorsConfigurationSource 对象
        CorsFilter corsFilter = new CorsFilter(source);

        //
        FilterRegistrationBean<CorsFilter> filterRegistrationBean=new FilterRegistrationBean<>(corsFilter);
        // 小于 SpringSecurity Filter的 Order(-100) 即可
        filterRegistrationBean.setOrder(-101);
        // 返回配置好的 FilterRegistrationBean。
        return filterRegistrationBean;
    }
}
